//
//  PMDataStatisticsViewController.m
//  Manager
//
//  Created by lvzhao on 2020/7/30.
//  Copyright © 2020 吕VV. All rights reserved.
//

#import "PMDataStatisticsViewController.h"
#import "LZBaseTableView.h"
#import "PMFinancialViewModel.h"
#import "PMDataStatisticsCell.h"
#import "PMOtherStaticCell.h"
#import "PMStatisticeDetailCell.h"
#import "PMScreeningViewController.h"


@interface PMDataStatisticsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) PMFinancialViewModel *viewModel;

@property (nonatomic,strong) LZBaseTableView *tableView;

@property (nonatomic,strong) NSIndexPath *selectIndexPath;

@end

@implementation PMDataStatisticsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self setupView];
    
    [self reloadRightItem];
}
    
//刷新右按钮
- (void)reloadRightItem{
    
    ///!!!:筛选
    self.navigationItem.rightBarButtonItem = nil;
    UIButton *screeningBtn = [UIButton lz_buttonImageName:@"pm_shaixuan" backgroundImageName:@""];
    screeningBtn.frame = CGRectMake(0, 0, 44, 44);
    [LZTool.currentViewController initBarItem:screeningBtn withType:1];
    [screeningBtn addTarget:self action:@selector(screenClick:) forControlEvents:UIControlEventTouchUpInside];
}

//筛选
- (void)screenClick:(UIButton *)sender{
    
    RACSubject *subject = [RACSubject subject];
    PMScreeningViewController *screeningVC = [[PMScreeningViewController alloc] init];
    screeningVC.pickerModel = PMDatePickerModelYM;
    screeningVC.reloadSubject = subject;
    [LZTool.currentViewController.navigationController pushViewController:screeningVC animated:YES];
    [subject subscribeNext:^(id  _Nullable x) {
        NSDictionary *dictionary = x;
        NSString *endTime = [[NSString stringWithFormat:@"%@",dictionary[@"endTime"]] componentsSeparatedByString:@" "].firstObject;
        NSString *startTime = [[NSString stringWithFormat:@"%@",dictionary[@"startTime"]] componentsSeparatedByString:@" "].firstObject;
        
        showLoadingTitle(@"", nil);
        [self.viewModel.paramsDictionary addEntriesFromDictionary:@{@"endTime":endTime?:@"",
                                                                    @"startTime":startTime?:@""}];
        [self.viewModel getDataStatistics:YES];
    }];
    

}

///设置
- (void)setupView{

    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    
    showLoadingTitle(@"", nil);
    [self.viewModel getDataStatistics:YES];
    
    @weakify(self);
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
         dismiss(nil);
         @strongify(self);
         [self reloadTable:[x intValue]];
     }];

}

///刷线表格
- (void)reloadTable:(NSInteger) type{
    
    
    switch (type) {
        case 1:{
            [self.tableView reloadData];
            [self.tableView dismissEmptyView];
        }
            break;
            
        case 2:{
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.selectIndexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
            break;
        case 3:
            {
                PMStatisticsModel *statisticsModel = self.viewModel.dataArray[self.selectIndexPath.section];
                if(statisticsModel.dataArray.count > self.selectIndexPath.row){
                    id model = statisticsModel.dataArray[self.selectIndexPath.row];
                    if([model isKindOfClass:[PMOtherStaticModel class]]){
                        PMOtherStaticModel *otherStaticModel = model;
                        //数据源
                        NSMutableArray *dataArray = [[NSMutableArray alloc] initWithArray:statisticsModel.dataArray];
                        if(!otherStaticModel.isConvert){
                            [dataArray removeObjectsInArray:otherStaticModel.dataArray];
                        }else {
                            NSInteger dataIndex = [dataArray indexOfObject:otherStaticModel];
                            [dataArray insertObjects:otherStaticModel.dataArray atIndex:dataIndex + 1];
                        }
                        statisticsModel.dataArray = dataArray;
                    }
                }
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.selectIndexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            break;
        default:
            break;
    }
    
    if(type > 3)return;
    if(self.viewModel.dataArray.count == 0){
        [self.tableView tableViewDisplayWithImgName:@"no_data" message:@"暂无数据" contentoffsetY:64 showEmptyView:YES];
    }
}



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.viewModel.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    PMStatisticsModel *statisticsModel = self.viewModel.dataArray[section];
    return statisticsModel.isConvert ? 1 : statisticsModel.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PMDataStatisticsCell *statisticsCell = [tableView dequeueReusableCellWithIdentifier:@"PMDataStatisticsCell"];
    PMOtherStaticCell *otherCell = [tableView dequeueReusableCellWithIdentifier:@"PMOtherStaticCell"];
    PMStatisticeDetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:@"PMStatisticeDetailCell"];
    
    PMStatisticsModel *statisticsModel = self.viewModel.dataArray[indexPath.section];
    if(indexPath.row == 0){
        statisticsCell.modelObject = statisticsModel;
        return statisticsCell;
    }
    if(statisticsModel.dataArray.count > indexPath.row){
    
        id model = statisticsModel.dataArray[indexPath.row];
        
        if([model isKindOfClass:[PMOtherStaticModel class]]){
            
            otherCell.modelObject = statisticsModel.dataArray[indexPath.row];
            return otherCell;

        } else {
            detailCell.modelObject = statisticsModel.dataArray[indexPath.row];
            return detailCell;
        }
    }
    return otherCell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
       // 这里要判断分组列表中的第一行，每组section的第一行，每组section的中间行

    // CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
    // 圆角弧度半径
    CGFloat cornerRadius = 6.f;
    // 设置cell的背景色为透明，如果不设置这个的话，则原来的背景色不会被覆盖
    cell.backgroundColor = UIColor.clearColor;

    // 创建一个shapeLayer
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
    // 创建一个可变的图像Path句柄，该路径用于保存绘图信息
    CGMutablePathRef pathRef = CGPathCreateMutable();
    // 获取cell的size
    // 第一个参数,是整个 cell 的 bounds, 第二个参数是距左右两端的距离,第三个参数是距上下两端的距离
    CGRect bounds = CGRectInset(cell.bounds, 15, 0);

    // CGRectGetMinY：返回对象顶点坐标
    // CGRectGetMaxY：返回对象底点坐标
    // CGRectGetMinX：返回对象左边缘坐标
    // CGRectGetMaxX：返回对象右边缘坐标
    // CGRectGetMidX: 返回对象中心点的X坐标
    // CGRectGetMidY: 返回对象中心点的Y坐标
    if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
        CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);

    } else if (indexPath.row == 0) {
        // 初始起点为cell的左下角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
        // 起始坐标为左下角，设为p，（CGRectGetMinX(bounds), CGRectGetMinY(bounds)）为左上角的点，设为p1(x1,y1)，(CGRectGetMidX(bounds),CGRectGetMinY(bounds))为顶部中点的点，设为p2(x2,y2)。然后连接p1和p2为一条直线l1，连接初始点p到p1成一条直线l，则在两条直线相交处绘制弧度为r的圆角。
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);

        // 终点坐标为右下角坐标点，把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
//      CGPathCloseSubpath(pathRef);

    } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
//
        // 初始起点为cell的左上角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
//      CGPathCloseSubpath(pathRef);
    } else {
        // 添加cell的rectangle信息到path中（不包括圆角）
        CGPathAddRect(pathRef, nil, bounds);

//        假如只要边框
//        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
//        CGPathAddLineToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
//        CGPathMoveToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
//        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
     }
    // 把已经绘制好的可变图像路径赋值给图层，然后图层根据这图像path进行图像渲染render
    layer.path = pathRef;
    backgroundLayer.path = pathRef;

    // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
    CFRelease(pathRef);
    // 按照shape layer的path填充颜色，类似于渲染render
    layer.lineWidth = 0;//线的宽度
    layer.strokeColor = COLOR_cellbackground.CGColor;//线的颜色
    layer.fillColor = COLOR_cellbackground.CGColor;//cellcell背景色
    // view大小与cell一致
    UIView *roundView = [[UIView alloc] initWithFrame:bounds];
    // 添加自定义圆角后的图层到roundView中
    [roundView.layer insertSublayer:layer atIndex:0];
    roundView.backgroundColor = UIColor.clearColor;
    // cell的背景view
    cell.backgroundView = roundView;
    cell.backgroundColor = [UIColor clearColor];
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PMStatisticsModel *statisticsModel = self.viewModel.dataArray[indexPath.section];
    if(indexPath.row == 0){
        return 50;
    }
    return 40;
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    sectionView.backgroundColor = COLOR_background;
    return sectionView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //处理开合表
    self.selectIndexPath = indexPath;
    PMStatisticsModel *statisticsModel = self.viewModel.dataArray[indexPath.section];
    if(indexPath.row == 0){
        statisticsModel.isConvert = !statisticsModel.isConvert;
        //请求数据
        [self.viewModel getSubStatistics:statisticsModel];
        return;
    }
    if(statisticsModel.dataArray.count > indexPath.row){
        id model = statisticsModel.dataArray[indexPath.row];
        if([model isKindOfClass:[PMOtherStaticModel class]]){
            PMOtherStaticModel *otherStaticModel = model;
            otherStaticModel.isConvert = !otherStaticModel.isConvert;
            [self.viewModel getDataStatisticsDetail:otherStaticModel];
            
        } else if ([model isKindOfClass:[PMStatisticeDetailModel class]]){
            return;
        }
    }
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView scrollToRow:indexPath.row inSection:indexPath.section atScrollPosition:UITableViewScrollPositionNone animated:NO];
}


#pragma mark -lanjiazai
- (LZBaseTableView *)tableView{
    if(!_tableView){
        _tableView = [[LZBaseTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = COLOR_background;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 50;
        [_tableView registerClass:[PMDataStatisticsCell class] forCellReuseIdentifier:@"PMDataStatisticsCell"];
        [_tableView registerClass:[PMOtherStaticCell class] forCellReuseIdentifier:@"PMOtherStaticCell"];
        [_tableView registerClass:[PMStatisticeDetailCell class] forCellReuseIdentifier:@"PMStatisticeDetailCell"];

        
    }
    return _tableView;
}

- (PMFinancialViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[PMFinancialViewModel alloc] init];
    }
    return _viewModel;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
